#########################################################################################################
#
# This script run the following analyses:
# 
# Interactions with market performance
# -------------------
# We compute the results for Table A38 and Table A39. 
# These tables present estimates from subsamples defined by market gains/losses since purchase 
# and since the peak price event. The analysis splits the sample based on whether the market 
# (FTSE100) experienced a loss or gain since the peak price event.

# - Table A38 focuses on cases where the market (FTSE100) was in loss since the purchase.
# - Table A39 focuses on cases where the market (FTSE100) was in gain since the purchase.


# Rebalancing Test:
# -----------------
# We also test for rebalancing by restricting the dependent variable to indicate complete sales only 
# (i.e., liquidation of positions), thereby excluding partial sales that might reflect portfolio rebalancing. 
# The results are shown in Table A35.

# Output Tables:
# --------------
# **Table A38: Estimates of the Stocks Disposition Effect (Sub-samples by FTSE100 Returns Since Purchase, Week-Peak, Sell-Day Sample)**
# - `tables/clean_ftse1_MAXC_peak_5update_sellsample.tex`

# **Table A39: Estimates of the Stocks Disposition Effect (Sub-samples by FTSE100 Returns Since Purchase, Week-Peak, Sell-Day Sample)**
# - `tables/clean_ftse2_MAXC_peak_5update_sellsample.tex`

# **Table A35: Estimates of the Stocks Disposition Effect (Excluding Partial Sells)**
# - `tables/clean_rebalancing_MAXC_peak_5update_sellsample.tex`
#
#########################################################################################################



data_for_peaks[is.na(flag_no_peak),percentiles50:=xtile(return.since.pur,n=50)]
data_for_peaks[is.na(flag_no_peak),percentiles_mean50:=mean(return.since.pur100), by=.(percentiles50)]


data_for_peaks[is.na(flag_no_peak),percentiles_point50:=xtile(return.since.point,n=50)]
data_for_peaks[is.na(flag_no_peak),percentiles_mean_point50:=mean(return.since.point100), by=.(percentiles_point50)]

{
  
  ftse100h <-
    fread("D:/files_moved_19/output datastream/datastream data/FTSE 100 Historical Data.csv")
  
  ftse100h[, port_date := as.Date(Date, "%B %d, %Y")]
  ftse100h[, price := as.numeric(gsub(',', '', `Close*`))]
  ftse100h[, price_adj := as.numeric(gsub(',', '',  `Adj Close**`))]
  
  ftse100h <- ftse100h[, .(port_date, price, price_adj)]
  
  days = data.table(port_date = unique(
    c(
      data_for_peaks$port_date,
      data_for_peaks$pur_day,
      data_for_peaks$date_past_point
    )
  ))
  ftse100h <- merge(ftse100h, days, by = c("port_date"), all.y = T)
  
  ftse100h <- ftse100h[order(port_date)]
  ftse100h <- ftse100h[, .(price, port_date)]
  setnames(ftse100h, "price", "priceftse100")
  ftse100h[, priceftse100 := na.locf(priceftse100, na.rm = F)]

 data_for_peaks[,":="(priceftse100=NULL,priceftse100pur=NULL, priceftse100point=NULL, return.since.pur.ftse100100=NULL,
                      return.since.point.ftse100100=NULL)]
  data_for_peaks[,.(pur_day, date_past_point, port_date)]
  data_for_peaks<-merge(data_for_peaks, ftse100h, by=c("port_date"), all.x=T)
  setnames(ftse100h,  "priceftse100", "priceftse100pur") 
  setnames(ftse100h,  "port_date", "pur_day") 
  
  
  data_for_peaks<-merge(data_for_peaks, ftse100h, by=c("pur_day"), all.x=T)
  
  setnames(ftse100h,  "priceftse100pur", "priceftse100point") 
  setnames(ftse100h,  "pur_day", "date_past_point") 
  
  
  data_for_peaks<-merge(data_for_peaks, ftse100h, by=c("date_past_point"), all.x=T)
  
  data_for_peaks[, return.since.pur.ftse100100:=100*(priceftse100- priceftse100pur)/ priceftse100pur]
  data_for_peaks[, return.since.point.ftse100100:=100*(priceftse100- priceftse100point  )/ priceftse100point]
  
  data_for_peaks[!is.na(return.since.pur.ftse100100), gain.since.pur.ftse100:=ifelse(return.since.pur.ftse100100>0, 1, 0)]
  data_for_peaks[!is.na(return.since.point.ftse100100),gain.since.point.ftse100:=ifelse(return.since.point.ftse100100 >0, 1, 0)] 

  data_for_peaks[, distance_pur:= as.numeric(port_date- pur_day)]
  data_for_peaks[, distance_pur100:= distance_pur/100]
  
  summary(m1c0<- felm(sell~gain.since.pur   + distance_pur100          | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==0]))
  
  summary(m2c0<- felm(sell~gain.since.point  + distance_pur100               | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==0]))
  
  summary(m3c0<- felm(sell~gain.since.pur + gain.since.point   + distance_pur100             | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==0]))
  
  
  
  summary(m1cf0<- felm(sell~gain.since.pur   + distance_pur100          | 0 | 0 | anon + port_date, 
                      data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==0]))
  
  summary(m2cf0<- felm(sell~gain.since.point + distance_pur100               | 0 | 0 | anon + port_date, 
                      data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==0]))
  
  summary(m3cf0<- felm(sell~gain.since.pur + gain.since.point     + distance_pur100           | 0 | 0 | anon + port_date, 
                      data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==0]))
  
  
  summary(m1c<- felm(sell~gain.since.pur   +  distance_pur100         | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==1]))
  
  summary(m2c<- felm(sell~gain.since.point   +  distance_pur100            | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==1]))
  
  summary(m3c<- felm(sell~gain.since.pur + gain.since.point    + distance_pur100            | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==0 & gain.since.point.ftse100==1]))
  

  
  summary(m1cf<- felm(sell~gain.since.pur    + distance_pur100         | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==1]))
  
  summary(m2cf<- felm(sell~gain.since.point + distance_pur100               | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==1]))
  
  summary(m3cf<- felm(sell~gain.since.pur + gain.since.point    + distance_pur100            | 0 | 0 | anon + port_date, 
                     data_for_peaks[gain.since.pur.ftse100==1 & gain.since.point.ftse100==1]))

  
  important_labels<- c( "Gain Since Purchase=1",
                        paste0(label_table_long, "=1"),
                        "Days from Purchase Day (100 days)"
  )
  
  # Table A38: Estimates of the Stocks Disposition Effect: Sub-samples by FTSE100 Returns Since Purchase (Week-Peak), Sell-Day Sample

    table<-stargazer( m1c0, m2c0, m3c0,  m1c, m2c, m3c,
                    title="", align=TRUE,type="latex",
                    dep.var.labels=c(""),
                    covariate.labels=important_labels,
                    omit        = NULL ,  
                    omit.stat=c("LL","ser","f", "adj.rsq") , 
                    omit.table.layout = "n",
                    float=F, 
                    table.layout ="-dc#-tas-",
                    style = "aer",
                    column.sep.width = "10pt",
                    digits=4 #
  )
  
  
  library(stringr)
  table <- str_replace_all(table, "\\^", "")
  table <- str_replace_all(table, "R\\$\\{2\\}\\$", "R$^{2}$")
  
  
  setwd(wd_tables)
  write.table(table[10:(length(table)-2)], col.names = F, 
              row.names = F, quote = FALSE, paste0("clean_ftse1_", plot_name, "_", use_days ,"sample.tex"))
  
  # Table A39: Estimates of the Stocks Disposition Effect: Sub-samples by FTSE100 Returns Since Purchase (Week-Peak), Sell-Day Sample
  
  table<-stargazer( m1cf0 , m2cf0, m3cf0,  m1cf, m2cf, m3cf,
                    title="", align=TRUE,type="latex",
                    dep.var.labels=c(""),
                    covariate.labels=important_labels,
                    omit        = NULL ,  
                    omit.stat=c("LL","ser","f", "adj.rsq") , 
                    omit.table.layout = "n",
                    float=F, 
                    table.layout ="-dc#-tas-",
                    style = "aer",
                    column.sep.width = "10pt",
                    digits=4 #
  )
  
  library(stringr)
  table <- str_replace_all(table, "\\^", "")
  table <- str_replace_all(table, "R\\$\\{2\\}\\$", "R$^{2}$")

  setwd(wd_tables)
  write.table(table[10:(length(table)-2)], col.names = F, 
              row.names = F, quote = FALSE, paste0("clean_ftse2_", plot_name, "_", use_days ,"sample.tex"))
  

}

# Testing for rebalancing

data_for_peaks[,sell.all:=0]
data_for_peaks[sell==1 & net.posit==0,sell.all:=1]

{
  summary(m1c<- felm(sell.all~gain.since.pur   + distance_pur100           | 0 | 0 | anon + port_date, 
                     data_for_peaks))
  
  summary(m2c<- felm(sell.all~gain.since.point  + distance_pur100               | 0 | 0 | anon + port_date, 
                     data_for_peaks))
  
  summary(m3c<- felm(sell.all~gain.since.pur + gain.since.point  + distance_pur100               | 0 | 0 | anon + port_date, 
                     data_for_peaks))
  

  summary(m1fec<- felm(sell.all~gain.since.pur  + distance_pur100           | anon | 0 | anon + port_date, 
                         data_for_peaks))
    
  summary(m2fec<- felm(sell.all~gain.since.point  + distance_pur100              | anon  | 0 | anon + port_date, 
                         data_for_peaks))
    
  summary(m3fec<- felm(sell.all~gain.since.pur + gain.since.point   + distance_pur100        | anon  | 0 | anon + port_date, 
                         data_for_peaks))

  # Table A35: Estimates of the Stocks Disposition Effect: Excluding Partial Sells    
    
    table<-stargazer( m1c, m2c, m3c,  m1fec, m2fec, m3fec,
                      title="", align=TRUE,type="latex",
                      dep.var.labels=c(""),
                      covariate.labels=important_labels,
                      omit        = NULL ,  
                      omit.stat=c("LL","ser","f", "adj.rsq") , 
                      omit.table.layout = "n",
                      float=F, 
                      table.layout ="-dc#-tas-",
                      style = "aer",
                      column.sep.width = "10pt",
                      add.lines=list(c("Account FE", "NO", "NO", "NO",  "YES", "YES","YES")) , #
                      digits=4 
    )
    
    
    library(stringr)
    table <- str_replace_all(table, "\\^", "")
    table <- str_replace_all(table, "R\\$\\{2\\}\\$", "R$^{2}$")
    
    setwd(wd_tables)
    write.table(table[10:(length(table)-2)], col.names = F, 
                row.names = F, quote = FALSE, paste0("clean_rebalancing_", plot_name, "_", use_days ,"sample.tex"))
    
    
    
}


